import * as turf from "@turf/turf";
import { Map as MapBoxMap } from "mapbox-gl";
import Base from "./Base";
import { ILayerProps } from "src/types/index";

export default class DrawLayer extends Base {
  layerId: string;
  layerIdPolygon: string;
  drawModesIdMap: Map<string, number[]>;
  constructor(map: MapBoxMap, layerProps: ILayerProps) {
    let SOURCE_NAME = "DrawLayer";
   
    super(map, layerProps, SOURCE_NAME);

    this.layerId = this.getLayerName("default")
    this.layerIdPolygon = this.getLayerName("polygon");
    this.drawModesIdMap = new Map();
    this.init();
  }

  init() {
    this.map.addSource(this.sourceId, {
      type: "geojson",
      data: turf.featureCollection(this.features) as any,
    });

    // 文字的样式【坐标、面积、距离、总长等】
    this.map.addLayer({
      id: this.layerId,
      type: "symbol",
      source: this.sourceId,
      layout: {
        "text-field": ["get", "tootip"], // 此属性对应图标注释,必须拥有
        "text-offset": [0, 1.25], // 设置图标与图标注相对之间的距离
        "text-font": [
          "literal",
          ["DIN Offc Pro Italic", "Arial Unicode MS Regular"],
        ],
      },
      paint: {
        "text-halo-color": "#2568AE",
        "text-halo-width": 1,
        "text-color": "#fff",
      },
    });

    // 缓冲面的样式
    this.map.addLayer({
      id: this.layerIdPolygon,
      type: "fill",
      source: this.sourceId,
      layout: {},
      paint: {
        "fill-color": "#0080ff", // blue color fill
        "fill-opacity": 0.5,
      },
    });
  }
  // 全并数据 通过 properties.drawId 对比新老 features
  mergeFeatures(Features: any, cb?: (v?: any) => any) {
    const newFeaturesIds = Features.map((e: any) => e.properties.drawId);
    let mergeFeatures = [
      ...this.features.filter(
        (e) => !newFeaturesIds.includes((e as any).properties.drawId)
      ),
      ...Features,
    ];
    this.updateFeatures(mergeFeatures, cb);
  }
  // 按drawId指定清除
  removeFeaturesByDrawIds(clearIds: number[]) {
    const newFeatures = this.features.filter(
      (e) => !clearIds.includes((e as any).properties.drawId)
    );
    if (newFeatures.length !== this.features.length) {
      this.updateFeatures(newFeatures);
    }
  }
}
